﻿namespace CocoaAni.Net.WebSockets.Tools;

internal class WSNetUtils
{
    public static int GetHttpHeaderEndIndex(byte[] data)
    {
        var responseHeaderEndIndex = -1;
        var isLastIsNewLine = false;
        for (var i = 0; i < data.Length; i++)
        {
            var temp = data[i];
            switch (temp)
            {
                case 13: continue;
                case 10:
                    if (isLastIsNewLine)
                    {
                        responseHeaderEndIndex = i; break;
                    }
                    isLastIsNewLine = true;
                    break;

                default: isLastIsNewLine = false; break;
            }
        }
        return responseHeaderEndIndex - 4;
    }

    public static Dictionary<string, object> ParseHeaders(string[] headerLines, ref Dictionary<string, object> output)
    {
        var result = output;
        foreach (var headerLine in headerLines)
        {
            if (string.IsNullOrEmpty(headerLine)) continue;
            var startTagIdx = headerLine.IndexOf(":", StringComparison.Ordinal);
            if (startTagIdx == -1)
            {
                throw new FormatException($"WSHandShakeResponse HeaderBuffer Is Error => [{headerLine}]");
            }
            result[headerLine[..startTagIdx].Trim()] = headerLine[(startTagIdx + 1)..].Trim();
        }
        return result;
    }
}